import { defineStore } from 'pinia';
import type { StitchedImage, StitchingOptions, ImageMetadata } from '../types/models';
import imageStitchingService from '../services/ImageStitchingService';
import { useUploadStore } from './uploadStore';

export const useStitchingStore = defineStore('stitching', {
  state: () => ({
    stitchedImage: null as StitchedImage | null,
    metadata: null as ImageMetadata | null,
    isStitching: false,
    stitchingProgress: 0,
    isDownloading: false,
    downloadProgress: 0,
    stitchingOptions: {
      arrangement: 'dynamic' as 'grid' | 'horizontal' | 'vertical' | 'dynamic',
      spacing: 0,
      maxWidth: 12000,
      maxHeight: 12000,
      backgroundColor: '#ffffff',
      allowRotation: true,
      targetSize: 12000
    } as StitchingOptions
  }),
  
  actions: {
    async stitchImages(options: StitchingOptions) {
      const uploadStore = useUploadStore();
      
      if (uploadStore.images.length === 0) {
        throw new Error('No images to stitch');
      }
      
      this.isStitching = true;
      this.stitchingProgress = 0;
      
      try {
        const stitchedImage = await imageStitchingService.stitchImages(
          uploadStore.images,
          options,
          (progress) => {
            this.stitchingProgress = progress;
          }
        );
        
        this.stitchedImage = stitchedImage;
        this.metadata = imageStitchingService.generateMetadata(uploadStore.images, stitchedImage, options);
        
        return stitchedImage;
      } finally {
        this.isStitching = false;
        this.stitchingProgress = 100;
      }
    },
    
    async downloadStitchedImage(
      stitchedImage: StitchedImage,
      format: string = 'png',
      quality: number = 0.9,
      filename?: string
    ) {
      this.isDownloading = true;
      this.downloadProgress = 0;
      
      try {
        await imageStitchingService.downloadStitchedImage(
          stitchedImage,
          format,
          quality,
          filename,
          (progress) => {
            this.downloadProgress = progress;
          }
        );
      } finally {
        this.isDownloading = false;
        this.downloadProgress = 100;
      }
    },
    
    downloadMetadata(metadata: ImageMetadata, filename?: string) {
      imageStitchingService.downloadMetadata(metadata, filename);
    }
  }
});